package com.andy.blog.framework.aspectj;

import com.alibaba.fastjson2.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * service调用入参日志切面
 * Created by andy on 2023/4/27 18:47
 */
@Aspect
@Component
public class ServiceParamLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(ServiceParamLogAspect.class);

    @Pointcut("execution(* com.andy.blog.*.service.bus.*.*BusService*.*(..))" +
            "|| execution(* com.andy.blog.*.service.bus.*.*DalService*.*(..))")
    public void serviceParamLog() {
    }

    /**
     * 请求入参打印
     *
     * @param joinPoint joinPoint
     */
    @Before("serviceParamLog()")
    public void paramServiceLog(JoinPoint joinPoint) {
        String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();
        List<Object> argsList = Arrays.asList(joinPoint.getArgs());
        String argListStr = JSON.toJSONString(argsList);
        logger.info("类名:[{}]|方法名:[{}]|入参:[{}]", declaringTypeName, methodName, argListStr);
    }

    /**
     * 请求结果返回打印
     */
    @AfterReturning(value = "serviceParamLog()", returning = "result")
    public void resultServiceLog(JoinPoint joinPoint, Object result) {
        String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();
        String resultStr = JSON.toJSONString(result);
        logger.info("类名:[{}]|方法名:[{}]|返回值:[{}]", declaringTypeName, methodName, resultStr);
    }

    /**
     * 异常处理切面
     */
    @AfterThrowing(value = "execution(* com.andy.blog.*.service.bus.*.*DalService*.*(..))", throwing = "ex")
    public void serviceThrowing(JoinPoint joinPoint, Exception ex) {
        String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();
        logger.error("类名:[{}]|方法名:[{}]抛出异常", declaringTypeName, methodName, ex);
    }
}
